/**
 * Created by Hayden on 2016/12/8.
 */

'use strict'

let express = require('express');
let exphbs = require('express-handlebars');
let bodyParser = require('body-parser');
let credentials = require('./credentials.js');
let cookieParser = require('cookie-parser');
let expressSession = require('express-session');

let users = [
  {name: 'hayden', age: '23', email: 'hayden@cfg.com'},
  {name: 'cfg0523', age: '24', email: 'cfg0523@cfg.com'},
  {name: 'chenchen', age: '25', email: 'chenchen@cfg.com'}
];

let app = express();
app.engine('hbs', exphbs.create({
  defaultLayout: 'main',
  extname: '.hbs'
}).engine);
app.set('view engine', 'hbs');

app.use(express.static('./public'));
app.use(cookieParser(credentials.cookieSecret));
app.use(expressSession({
  key: 'esessionid',
  cookie: {
    path: '/',
    domain: 'localhost',
    httpOnly: true
  }
}));
app.use(bodyParser());

app.use(function (req, res, next) {
  res.locals = { users };
  next();
});

app.get('/users', function (req, res) {
  console.log(`cookies: ${JSON.stringify(req.cookies)}`);
  console.log(`signedCookies: ${JSON.stringify(req.signedCookies)}`);
  res.render('home', {csrf: 'csrf value in here'});
});

app.post('/user', function(req, res) {
  let name = req.body.name,
      age = req.body.age,
      email = req.body.email;
  users.push({name, age, email});
  res.cookie('myweb-name', 'MyWEB', { signed: true});
  res.redirect(303, '/users');
});

app.use(function (req, res) {
  res.status(404).render('404');
});

app.use(function (err, req, res, next) {
  res.status(500).render('500');
});

app.listen(8080, () => {
  console.log('server listen http-8080');
});